﻿using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using RTW.Core.Extensions;
using RTW.Models;
using RTW.Servers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace RTW.Web.Comm
{
    public class CommController: BaseController
    {
        /// <summary>
        /// 请求过滤处理
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            byte[] result;
            filterContext.HttpContext.Session.TryGetValue("User", out result);
            if (result == null)
            {
                filterContext.Result = new RedirectResult("/Login");
                return;
            }
            base.OnActionExecuting(filterContext);
        }


        public UserServer _userServer;
        public SysLogServer _sysLogServer;
        public ErrLogServer _errlogServer;
        public CommController()
        {           
            _userServer = new UserServer();
            _sysLogServer = new SysLogServer();
            _errlogServer = new ErrLogServer();
        }

        public void AddLog(string content,string logtype,string url)
        {
            TLog model = new TLog();
            // model.ID = GetID;
            model.ID = Guid.NewGuid().ToString("N");
            model.LogInfo = content;
            model.Modular = logtype;
            model.PageUrl = url;
            model.UserID = UserID;
            model.AddTime = DateTime.Now;
            model.Bak1 = GetHostAddress();
            model.DMID = UserDMID;
            _sysLogServer.Insert(model);
        }

        /// <summary>
        /// 添加错误日志信息
        /// </summary>
        /// <param name="Msg">描述</param>
        /// <param name="PageUrl">页面</param>
        public void AddErrLog(string Msg, string dmid)
        {
            //string userid = "";
            //if (Session["User"] != null)
            //{
            //    userid = UserID;
            //}
            string url =Request.GetAbsoluteUri();
            //DossierDB.DAL.TErrLog bll = new DossierDB.DAL.TErrLog();
            //DossierDB.Model.TErrLog model = new DossierDB.Model.TErrLog();
            TErrLog model = new TErrLog();
            model.ID = Guid.NewGuid().ToString("N");
            model.Msg = Msg;
            model.PageUrl = url;
            model.UserID = UserID;
            model.UserIP = GetHostAddress();
            model.AddTime = DateTime.Now;
            model.DMID = dmid;
            _errlogServer.Insert(model);
        }

        /// <summary>
        /// 用户编号
        /// </summary>
        public string UserID
        {
            get
            {
                if (this.HttpContext.Session.GetObjectFromJson<TUserInfo>("User") != null)
                {
                    string User = this.HttpContext.Session.GetObjectFromJson<TUserInfo>("User").ID.ToString();
                    return User;
                }
                else
                {
                    //默认值，方便调试
                    this.HttpContext.Session.Clear();
                   // ShowTips("您未登录，或者登录信息过期，请重新登录!", 4);

                    return "";
                }
            }
        }

        public string UserDMID {
            get
            {
                if (this.HttpContext.Session.GetObjectFromJson<TUserInfo>("User") != null)
                {
                    string DMID = this.HttpContext.Session.GetObjectFromJson<TUserInfo>("User").DMID;
                    return DMID;
                }
                else
                {
                    //默认值，方便调试
                    this.HttpContext.Session.Clear();
                    //ShowTips("您未登录，或者登录信息过期，请重新登录!", 4);

                    return "";
                }
            }
        }

        /// <summary>
        /// 用户账号
        /// </summary>
        public string UserAccount
        {
            get
            {
                if (this.HttpContext.Session.GetObjectFromJson<TUserInfo>("User") != null)
                {
                    string User = this.HttpContext.Session.GetObjectFromJson<TUserInfo>("User").UserAccount.ToString();
                    return User;
                }
                else
                {
                    //默认值，方便调试
                    this.HttpContext.Session.Clear();
                    // ShowTips("您未登录，或者登录信息过期，请重新登录!", 4);

                    return "";
                }
            }
        }

        /// <summary>
        /// 用户信息
        /// </summary>
        public TUserInfo UserInfo
        {
            get
            {
                if (HttpContext.Session.GetObjectFromJson<TUserInfo>("User") != null)
                {
                    TUserInfo User = HttpContext.Session.GetObjectFromJson<TUserInfo>("User");
                    return User;
                }
                else
                {
                    HttpContext.Session.Clear();
                  //  ShowTips("您未登录，或者登录信息过期，请重新登录!", 4);

                    return null;
                }
            }
        }


        /// <summary>
        /// 获取客户端IP地址（无视代理）
        /// </summary>
        /// <returns>若失败则返回回送地址</returns>
        public string GetHostAddress()
        {
            string userHostAddress = (Request.HttpContext.Connection.LocalIpAddress.MapToIPv4().ToString() + ":" + Request.HttpContext.Connection.LocalPort);


            if (string.IsNullOrEmpty(userHostAddress))
            {
                //userHostAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                userHostAddress= HttpContext.Connection.RemoteIpAddress.ToString();
            }

            //最后判断获取是否成功，并检查IP地址的格式（检查其格式非常重要）
            if (!string.IsNullOrEmpty(userHostAddress) && IsIP(userHostAddress))
            {
                return userHostAddress;
            }
            return "127.0.0.1";
        }
        /// <summary>
        /// 检查IP地址格式
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public bool IsIP(string ip)
        {
            return System.Text.RegularExpressions.Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
        }


  
    }

}
